import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';
const app = getApp();
Page({
  data: {
    defaultData: {
      title: "报表模板", // 导航栏标题
      imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    templateList: [],
    pageNum: 0,
    pageSize: 10,
    isEmpty: false,
    radio: '1',
    selectAddress: "",
    fromPage: null,
  },
  onLoad(options) {
    if (options.fromPage) {
      this.setData({
        fromPage: options.fromPage
      });
      console.log("options.fromPage", this.data.fromPage);
    }
  },

  onShow() {
    // this.getAddress()
    this.getReportTemplatesByUser()
    console.log("dfgdg");
  },

  //获取模板列表
  async getReportTemplatesByUser() {
    const pageNum = 1;
    const pageSize = 1000;
    try {
      const res = await request({
        url: indexApi.getReportTemplatesByUserApi(pageNum, pageSize),
        data: {}
      });

      let templateList = res.data.records;

      if (templateList.length === 0) {
        console.log("为空");
        this.setData({
          isEmpty: false
        });
      } else {
        // 查找是否有 isDefault 为 1 的模板
        const defaultTemplate = templateList.find(item => item.isDefault === 1);

        if (defaultTemplate) {
          // 过滤掉 isDefault 为 1 的模板，并将它放到数组顶部
          templateList = [
            defaultTemplate,
            ...templateList.filter(item => item.isDefault !== 1)
          ];
        }

        this.setData({
          templateList,
          isEmpty: true
        });
      }

      console.log("获取模板列表", this.data.templateList);
    } catch (error) {
      console.error("Error:", error);
    }
  },


  //选择地址
  onChange(event) {
    const selectAddress = event.currentTarget.dataset.address
    this.setData({
      radio: event.detail,
      selectAddress: selectAddress
    });
    console.log("selectAddress", this.data.selectAddress);
  },


  //删除模板
  async delReportTemplate(templateid) {
    const id = templateid
    try {
      const res = await request({
        url: indexApi.delReportTemplateApi(),
        method: "POST",
        data: {
          id
        }
      });
      console.log(res);
      if (res.code == 200) {
        wx.showToast({
          title: "删除成功",
          icon: "none",
        });
      }
      this.getReportTemplatesByUser()

    } catch (error) {
      console.error("Error:", error);
    }
  },

  //点击删除按钮
  async onClose(event) {
    const {
      position,
      instance
    } = event.detail;
    console.log("event.currentTarget.dataset.addressid", event.currentTarget.dataset);
    const templateid = event.currentTarget.dataset.templateid;
    if (position === 'right') {
      wx.showModal({
        title: '删除确认',
        content: '确认删除该模板吗？',
        success: (res) => {
          if (res.confirm) {
            this.delReportTemplate(templateid).then(() => {
              instance.close(); // 确保在删除成功后关闭 swipe-cell
            }).catch(() => {
              instance.close();
            });
          } else {
            instance.close();
          }
        }
      });
    }
  },

  //修改模板
  templateChange(event) {
    // console.log("修改模板", event.currentTarget.dataset.templateitem);
    const templateItem = event.currentTarget.dataset.templateitem;
    wx.navigateTo({
      url: `/packageUserCenter/pages/addTemplate/index?templateItem=${encodeURIComponent(JSON.stringify(templateItem))}`,
    })
  },

  //确认
  beSure() {
    if (this.data.fromPage == 1) {
      if (Object.keys(this.data.selectAddress).length === 0) {
        wx.showToast({
          title: "请选择一个地址",
          icon: "none",
        });
        return;
      }
      app.globalData.selectedAddress = this.data.selectAddress;
      console.log("app.globalData.selectedAddress", app.globalData.selectedAddress);
      wx.navigateBack()

    } else {
      wx.navigateBack()
    }
  },

  //添加模板
  toAddAddress() {
    wx.navigateTo({
      url: '/packageUserCenter/pages/addTemplate/index?fromPage=2',
    })
  },
  toBack() {
    wx.navigateBack({
      delta: 1
    });
  }
})